<!-- eslint-disable new-cap -->
<template>
  <div class="a-menu">
    <div class="menus-table">
      <div class="menus">
        <div class="item home" @click="choiceMenuFun('/', 'home', 'app')" @contextmenu.prevent="showRightMenu($event, -2)">
          <img src="../assets/icon/svg/home.svg" class="active" />
        </div>
        <div style="background: #c6c6c6;margin: 10px 0;height: 2px;"></div>
        <div class="item chat" @click="choiceMenuFun('/chat', 'chat', 'app')" @contextmenu.prevent="showRightMenu($event, -1)">
          <img src="../assets/icon/svg/chat.svg" :class="{ active: choiceMenu == '/chat' }" />
        </div>
        <div class="active-app">
          <div class="item" @click="choiceMenuFun(app.url, app.name, app.type)" v-for="(app, index) in activeApps"
            @contextmenu.prevent="showRightMenu($event, index)" :key="index">
            <img :src="app.icon" :class="{
          active: choiceMenu == app.url || rightMenu.index == index
        }" :title="app.title" />
          </div>
        </div>
        <div class="item setting" @click="choiceMenuFun('/setting/theme', 'setting', 'app')">
          <img src="../assets/icon/menu/a-menu-setting.png" :class="{ active: choiceMenu == '/setting/theme' }"
            title="设置" />
        </div>
      </div>
    </div>
    <div class="vpopmenu" v-if="rightMenuStyle.show" :style="{
          top: rightMenuStyle.top + 'px',
        }">
      <div @click="defaultHome()" style="display: flex;align-items: center;">
        <i class="fa-solid fa-display "></i>
        <span style="margin-left: 4px;"> {{ this.rightMenu.app.defaultHome ? '取消主页' : '默认主页' }}</span>
      </div>
      <div @click="appFit()" style="display: flex;align-items: center;">
        <i class="fa-regular fa-star " v-if="this.rightMenu.app.fitMenu && !this.rightMenu.app.defaultHome"></i>
        <i class="fa-solid fa-star " v-else></i>
        <span style="margin-left: 4px;"> {{ this.rightMenu.app.fitMenu ? '取消固定' : '固定图标' }}</span>
      </div>
      <div @click="reloadApp()" v-if="this.rightMenu.app.url == this.choiceMenu &&
          this.rightMenu.app.type != 'web'
          " style="display: flex;align-items: center;">
        <i class="fa-solid fa-arrows-rotate "></i>
        <span style="margin-left: 4px;">重新打开</span>
      </div>
      <div @click="closeApp()" v-if="!this.rightMenu.app.fitMenu" style="display: flex;align-items: center;">
        <i class="fa-regular fa-circle-xmark "></i>
        <span style="margin-left: 4px;">关闭</span>
      </div>
    </div>
  </div>
</template>

<script>
// 加载模块
import { globalBus } from "@/assets/js/globalBus.js";

const nedb = require("nedb");
// 实例化连接对象（不带参数默认为内存数据库）
// eslint-disable-next-line new-cap
const db = new nedb({
  filename: "/data/menu.db",
  autoload: true
});
// 对索引设置唯一性约束
db.ensureIndex(
  {
    fieldName: "url",
    unique: true
  },
  function (_err) { }
);
export default {
  inject: ["reload"],
  components: {},
  data() {
    return {
      choiceMenu: "/",
      choiceMenuName: "/",
      activeApps: [],
      rightMenuStyle: {
        left: 0,
        show: false
      },
      rightMenu: {
        index: "-1",
        app: {}
      }
    };
  },
  beforeDestroy() {
    globalBus.$off("openApp", this.openApp);
  },
  created() {
    globalBus.$on("openApp", this.openApp);
  },
  methods: {
    openApp(app) {
      this.appType = app.type;
      for (var x in this.activeApps) {
        if (app.url === this.activeApps[x].url) {
          if (app.type === "web") {
            app.name = "webView";
            this.choiceMenuName = app.name;
            this.choiceMenu = app.url;
            this.$router
              .push({
                path: "/",
                query: { url: app.url, type: "web" }
              })
              .catch(err => {
                console.log(err);
              });
            return;
          }

          this.choiceMenuName = app.name;
          this.choiceMenu = app.url;
          this.$router.push({ path: app.url, query: app.query }).catch(err => {
            console.log(err);
          });
          return;
        }
      }
      if (app.type === "app") {
        this.activeApps.push(app);
        this.choiceMenuName = app.name;
        this.choiceMenu = app.url;
        this.$router.push({ path: app.url, query: app.query }).catch(err => {
          console.log(err);
        });
      } else if (app.type === "web") {
        app.name = "webView";
        this.activeApps.push(app);
        this.choiceMenuName = app.name;
        this.choiceMenu = app.url;
        this.$router
          .push({
            path: "/",
            query: { url: app.url, type: "web" }
          })
          .catch(err => {
            console.log(err);
          });
      }
      this.$store.commit("iskeepAlive", app.name);
    },
    reloadApp() {
      var _this = this;
      this.$store.commit("noKeepAlive", this.choiceMenuName);
      this.$router.push("/reload").catch(_err => { });
      setTimeout(function () {
        if (_this.appType === "web") {
          _this.$router
            .push({
              path: "/",
              query: { url: _this.choiceMenu, type: "web", operation: "reload" }
            })
            .catch(_err => { });
          return;
        }

        _this.$router.push(_this.choiceMenu).catch(_err => { });
        _this.$store.commit("iskeepAlive", this.choiceMenuName);
      }, 1000);
    },
    closeApp() {
      var app = this.activeApps[this.rightMenu.index];
      this.activeApps.splice(this.rightMenu.index, 1);
      if (app.type === "web") {
        this.$router
          .push({
            path: "/",
            query: { url: app.url, type: "web", operation: "remove" }
          })
          .catch(_err => { });
        return;
      }

      this.$store.commit("noKeepAlive", app.name);
      if (this.choiceMenu === app.url) {
        this.choiceMenu = "/";
        this.$router.push("/").catch(_err => { });
      }
    },
    removeAppFit(index) {
      var app = this.activeApps[this.rightMenu.index];
      app.fitMenu = false;
      db.remove(
        {
          url: app.url
        },
        {},
        (_err, _ret) => { }
      );
    },
    appFit(index) {
      var app = this.activeApps[this.rightMenu.index];
      app.fitMenu = true;
      db.insert(app, (_err, _ret) => { });
    },
    defaultHome() {
      var app = this.activeApps[this.rightMenu.index];
      app.defaultHome = !app.defaultHome;
      app.fitMenu = app.defaultHome;

      if (app.defaultHome) {
        // 更新操作
        db.update(
          { defaultHome: true }, // 查询条件
          { $set: { defaultHome: false } }, // 更新的内容
          { multi: true }, // 如果设置为 true，将会更新所有匹配的文档
          (_err, _ret) => { }
        );
      }
      if (app._id) {
        // 更新操作
        db.update(
          { _id: app._id }, // 查询条件
          { $set: { defaultHome: app.defaultHome } }, // 更新的内容
          {},
          (_err, _ret) => { }
        );
      } else {
        db.insert(app, (_err, _ret) => { });
      }

    },
    // 点击应用图标
    choiceMenuFun(url, name, type) {
      this.rightMenu.index = "-1";
      this.choiceMenu = url;
      this.choiceMenuName = name;
      this.appType = type;
      if (type === "web") {
        this.$router
          .push({
            path: "/",
            query: { url: url, type: "web" }
          })
          .catch(_err => { });
        return;
      }

      this.$router.push(url).catch(_err => { });
    },
    showRightMenu(e, index) {
      this.rightMenu.index = index;
      this.rightMenu.app = this.activeApps[index];
      this.rightMenuStyle.top = e.clientY - 60;
      if (this.rightMenuStyle.top + 130 > e.view.innerHeight) {
        this.rightMenuStyle.top = e.view.innerHeight - 130;
      }
      this.rightMenuStyle.show = true;
    },
    clickOther(e) {
      this.rightMenu.index = "-1";
      this.rightMenuStyle.show = false;
    }
  },
  mounted() {
    var _this = this;
    window.addEventListener("click", this.clickOther);
    db.find({}, function (_err, docs) {
      _this.activeApps = docs;
      for (var x in docs) {
        if (_this.$route.path === docs[x].url) {
          _this.choiceMenuFun(_this.$route.path);
          return;
        } else if (docs[x].defaultHome) {
          _this.choiceMenuFun(docs[x].url);
          return;
        }
      }
      _this.choiceMenuFun("/");
    });
  }
};
</script>

<style lang="less">
.theme-dark {
  .a-menu {
    .menus-table {
      .menus {
        background: #000;
      }
    }

    .vpopmenu {
      background: #000;
    }
  }
}

.theme-light {
  .a-menu {
    .menus-table {
      .menus {
        background: #000;
      }
    }

    .vpopmenu {
      background: #000;
    }
  }
}

.a-menu {
  position: relative;
  height: 100%;
  display: table;

  .vpopmenu {
    z-index: 99;
    position: absolute;
    left: 100%;
    padding: 10px;
    border-top-right-radius: 6px;
    border-bottom-right-radius: 6px;
    box-shadow: 6px 0px 10px rgba(255, 255, 255, 0.2);
    transition: display 0.3s linear;

    .fa {
      line-height: 1.4rem;
      width: 1.2rem;
    }

    div {
      transition: all 0.2s linear;
      margin: 4px 0;
      cursor: pointer;
      color: #69849b;
      display: flex;
      white-space: nowrap;
    }

    div:hover {
      color: #29b6f6;
    }

    .delete:hover {
      color: #f4511e;
    }
  }

  .menus-table {
    display: table-cell;
    vertical-align: middle;

    .menus {
      box-sizing: border-box;
      height: 100%;
      width: calc(1.8rem + 20px);
      position: relative;
      display: flex;
      flex-direction: column;
      transition: all 0.2s ease-in-out;
      padding: 20px 10px;
      margin-left: auto;
      margin-right: auto;
      border-radius: 10px;
      background: #ffffff;
      box-shadow: 0px 0px 2px rgba(0, 0, 0, 0.1);

      .active-app {
        padding: 10px 0;
        flex: 1;
      }

      .home {
        /* position: absolute;
          top: 0.8rem; */
      }

      .setting {
        /* position: absolute;
          bottom: 0.2rem; */
      }

      .item {
        box-sizing: border-box;
        text-align: center;
        position: relative;
        border-radius: 10px;
        height: 2.4rem;

        img {
          cursor: pointer;
          transition: all 0.1s linear;
          border-radius: 4px;
          height: auto;
          width: 1.4rem;
          -webkit-filter: grayscale(100%);
          -moz-filter: grayscale(100%);
          -ms-filter: grayscale(100%);
          -o-filter: grayscale(100%);
          filter: grayscale(100%);
          filter: gray;

          max-width: 100%;
          max-height: 100%;
          position: absolute;
          left: 50%;
          top: 50%;
          transform: translate3d(-50%, -50%, 0);
          -webkit-transform: translate3d(-50%, -50%, 0);
        }

        .active,
        img:hover {
          margin-left: 0;
          // margin-top: 0.3rem;
          width: 1.8rem;
          -webkit-filter: grayscale(0%);
          -moz-filter: grayscale(0%);
          -ms-filter: grayscale(0%);
          -o-filter: grayscale(0%);
          filter: grayscale(0%);
          filter: none;
        }
      }
    }

    .menus:hover {
      box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.2);
    }
  }
}
</style>
